package hn.cch.spring.boot.controller;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@RequestMapping(value = "/io")
@RestController
public class DownloadController {

    private static final Logger logger = LoggerFactory.getLogger(DownloadController.class);

    /**
     * 对于文件下载，以下两种实现方式只是针对小文件，
     * 对于文件大小较大的建议
     * 1.前端直接访问本地文件
     * 2.使用ftp/sftp下载文件
     * 3.使用nginx
     */
//    @GetMapping(value = "downloadZip")
//    public ResponseEntity<byte[]> downloadZip() {
//        File zipFile = new File("下载多文件压缩包.zip");
//
//        try {
//            ClassPathResource classPathResource = new ClassPathResource("static/png.png");
//            // File file = ResourceUtils.getFile("classpath:static/png.png");
//            File file = classPathResource.getFile();
//            // 读取文件夹下所有文件
//            File[] fileArray = file.getParentFile().listFiles();
//            List<File> fileList = new ArrayList<>();
//            if (fileArray != null) {
//                fileList = Arrays.asList(fileArray);
//            }
//
//            // 压缩文件
//            ZipFileUtil.compressZip(zipFile, fileList, "");
//            // 读取压缩包
//            byte[] body = FileUtils.readFileToByteArray(zipFile);
//
//            // 返回文件二进制流
//            String fileName = URLEncoder.encode(zipFile.getName(), "UTF-8");
//            HttpHeaders headers = new HttpHeaders();
//            headers.set("download", "true");
//            headers.add("Content-Disposition", "attachment;filename=" + fileName);
//            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//            headers.setContentLength(body.length);
//            return new ResponseEntity<>(body, headers, HttpStatus.OK);
//
//        } catch (Exception e) {
//            logger.error("download Exception:", e);
//            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
//        } finally {
//            // 删除压缩包
//            FileUtils.deleteQuietly(zipFile);
//        }
//
//    }


    @GetMapping(value = "downloadFile")
    public void downloadFile(HttpServletResponse response) {

        ServletOutputStream servletOutputStream = null;
        try {
            // 读取本地文件
            ClassPathResource classPathResource = new ClassPathResource("static/png.png");
            File file = classPathResource.getFile();
            byte[] bytes = FileUtils.readFileToByteArray(file);
            // 设置响应头部
            String fileName = URLEncoder.encode(file.getName(), "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            // 获取响应输出流
            servletOutputStream = response.getOutputStream();
            // 将文件写入输出流
            servletOutputStream.write(bytes);
            servletOutputStream.flush();

        } catch (IOException e) {
            logger.error("download Exception:", e);
        } finally {
            // 关闭响应输出流
            IOUtils.closeQuietly(servletOutputStream);
        }
    }


}

